<template>
  <div class="category-form-container">
    <el-card class="form-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <h3 class="form-title">新增商品分类</h3>
        </div>
      </template>

      <el-form
        label-width="120px"
        class="category-form"
        :model="category"
      >
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="分类名称">
              <el-input
                v-model="category.name"
                placeholder="请输入分类名称"
              />
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="父分类 ID">
              <el-input
                v-model="category.parentId"
                placeholder="请输入父分类 ID（若为顶级分类，输入 0）"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item class="action-buttons">
          <el-button
            type="primary"
            @click="addCategory"
          >
            保存分类
          </el-button>
          <el-button
            type="text"
            @click="goback"
          >
            返回
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import { reactive } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'
import router from '@/router'

// 分类数据
const category = reactive({
  name: '',
  parentId: 0
})

// 新增分类
function addCategory() {
  // 简单验证
  if (!category.name) {
    ElMessage.warning('请输入分类名称')
    return
  }

  axios.post('/tCategory', category).then(res => {
    if (res.data.code === 200) {
      ElMessage.success('分类添加成功')
      // 可以在这里进行页面跳转等操作
    } else {
      ElMessage.error(res.data.message || '分类添加失败，请稍后重试')
    }
  }).catch(error => {
    ElMessage.error('分类添加失败，请稍后重试')
    console.error('分类添加失败:', error)
  })
}

// 返回上一页
function goback() {
  router.back()
}
</script>

<style scoped>
.category-form-container {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
}

.form-card {
  background-color: var(--el-bg-color);
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
}

.form-card:hover {
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
}

.card-header {
  padding-bottom: 16px;
}

.form-title {
  font-size: 20px;
  font-weight: 600;
  color: var(--el-text-color-primary);
}

.category-form {
  padding: 16px 0;
}

.action-buttons {
  display: flex;
  gap: 16px;
  padding-top: 20px;
}

.el-button {
  min-width: 100px;
}

.el-form-item__label {
  font-weight: 500;
}
</style>